
using Microsoft.AspNetCore.StaticFiles;
using UniversalAdmin.Application;
using UniversalAdmin.Infrastructure;
using UniversalAdmin.Shared.Constants;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using UniversalAdmin.Domain.Entities.App;
using UniversalAdmin.Domain.Repositories;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddHttpContextAccessor();

// 使用扩展方法注册 Infrastructure 服务
builder.Services.AddInfrastructure(builder.Configuration);

builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("Jwt"));

// 添加JWT认证
var jwtSettings = builder.Configuration.GetSection("Jwt").Get<JwtSettings>();
if (jwtSettings != null)
{
    var key = Encoding.UTF8.GetBytes(jwtSettings.SecretKey);
    
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = true,
            ValidIssuer = jwtSettings.Issuer,
            ValidateAudience = true,
            ValidAudience = jwtSettings.Audience,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(jwtSettings.ClockSkewSeconds)
        };
    });
}

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins(["http://localhost:5173"])
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials();
    });
});

builder.Services.AddApplication(builder.Configuration);
builder.Services.AddScoped<UniversalAdmin.Application.Services.Interfaces.IUserContextService, UniversalAdmin.Application.Services.Implementations.UserContextService>();

var app = builder.Build();

// 启用静态文件服务，并为.txt文件加charset=utf-8，避免中文乱码
var provider = new FileExtensionContentTypeProvider();
// 强制 .txt 文件为 utf-8
provider.Mappings[".txt"] = "text/plain; charset=utf-8";
// 添加其他文本文件类型的UTF-8支持
provider.Mappings[".log"] = "text/plain; charset=utf-8";
provider.Mappings[".md"] = "text/markdown; charset=utf-8";

app.UseStaticFiles(new StaticFileOptions
{
    ContentTypeProvider = provider,
    OnPrepareResponse = ctx =>
    {
        // 为文本文件添加额外的响应头，确保浏览器正确解析
        if (ctx.File.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
        {
            ctx.Context.Response.Headers.Append("Content-Type", "text/plain; charset=utf-8");
        }
    }
});

app.UseCors();

// 启用认证和授权中间件
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
